package com.rabbit.message.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * rabbitMQ 配置
 * 绑定交换机与队列
 * @author pyong
 *
 */
@Configuration
public class RabbitMQConfig {

    /**
     * key: queue在该direct-exchange中的key值，当消息发送给direct-exchange中指定key为设置值时，
     * 消息将会转发给queue参数指定的消息队列
     */
    /** 路由key*/
    public static final String ROUTING_KEY_1 = "queue_key_1";
    public static final String ROUTING_KEY_2 = "queue_key_2";
    public static final String ROUTING_KEY_3 = "queue_key_3";

    /**队列名称*/
    public final static String QUEUE_NAME1 =  "first_queue";
    public static final String QUEUE_NAME2 = "second_queue";
    public static final String QUEUE_NAME3 = "thrid_queue";

    /**交换机*/
    public static final String EXCHANGE_01 = "first_exchange";
    public static final String EXCHANGE_02 = "second_exchange";
    public static final String EXCHANGE_03 = "third_exchange";

    /**
     * 将消息队列1和交换机1进行绑定,指定队列key1
     */
    @Bean
    public Binding binding_one() {
        return BindingBuilder.bind(firstQueue()).to(directExchange()).with(ROUTING_KEY_1);
    }
    @Bean
    public Binding binding_two(){
        return BindingBuilder.bind(secondQueue()).to(fanoutExchange());
    }
    @Bean
    public Binding binding_three(){
        return BindingBuilder.bind(thirdQueue()).to(topicExchange()).with(ROUTING_KEY_2);
    }



    /**
     *   1.定义direct exchange，绑定first_exchange
     *   2.durable="true" 持久化交换机， rabbitmq重启的时候不需要创建新的交换机
     *   3.direct交换器，匹配规则为：如果路由键匹配，消息就被投送到相关的队列
     *     fanout交换器中没有路由键的概念，他会把消息发送到所有绑定在此交换器上面的队列中。
     *     topic交换器采用模糊匹配路由键的原则进行转发消息到队列中
     */
    @Bean
    public DirectExchange directExchange(){
        DirectExchange directExchange = new DirectExchange(EXCHANGE_01,true,false);
        return directExchange;
    }
    @Bean
    public FanoutExchange fanoutExchange(){
        FanoutExchange fanoutExchange = new FanoutExchange(EXCHANGE_02,true,false);
        return fanoutExchange;
    }
    @Bean
    public TopicExchange topicExchange(){
        TopicExchange topicExchange = new TopicExchange(EXCHANGE_03,true,false);
        return topicExchange;
    }



    /**
     * durable="true" 持久化消息队列 ， rabbitmq重启的时候不需要创建新的队列
     * auto-delete 表示消息队列没有在使用时将被自动删除 默认是false
     * exclusive  表示该消息队列是否只在当前connection生效,默认是false
     **/
    @Bean
    public Queue firstQueue(){
        return new Queue(QUEUE_NAME1,true,false,false);
    }

    @Bean
    public Queue secondQueue(){
        return new Queue(QUEUE_NAME2,true,false,false);
    }
    @Bean
    public Queue thirdQueue(){
        //配置自动删除
        Map<String,Object> arguments = new HashMap<>();
        arguments.put("x-messgae-ttl",60000);
        return new Queue(QUEUE_NAME3,true,false,true,arguments);
    }
}
